package com.programmercarl.dp;

/**
 * https://leetcode.cn/problems/last-stone-weight-ii/
 * 1049.最后一块石头的重量II AC
 *
 * @author 田雨龙
 * @create 2025-02-17 20:44
 */
public class Test09 {
    public static void main(String[] args) {

    }

    /**
     * 二维dp
     *
     * @param stones
     * @return
     */
    public int lastStoneWeightII(int[] stones) {
        int n = stones.length;
        if (n == 1) {
            return stones[0];
        }
        int bag = 0;
        for (int i = 0; i < n; i++) {
            bag += stones[i];
        }
        int[][] dp = new int[n][bag + 1];
        // 初始化
        for (int j = 2 * stones[0]; j <= bag; j++) {
            dp[0][j] = stones[0] * 2;
        }

        for (int i = 1; i < n; i++) {
            for (int j = 1; j <= bag; j++) {
                if (j < 2 * stones[i]) {
                    dp[i][j] = dp[i - 1][j];
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 2 * stones[i]] + 2 * stones[i]);
                }
            }
        }
        return bag - dp[n - 1][bag];
    }

    /**
     * 滚动数组
     *
     * @param stones
     * @return
     */
    public int lastStoneWeightII2(int[] stones) {
        int n = stones.length;
        if (n == 1) {
            return stones[0];
        }
        int bag = 0;
        for (int i = 0; i < n; i++) {
            bag += stones[i];
        }
        // 滚动数组
        int[] dp = new int[bag + 1];
        for (int i = 0; i < n; i++) {
            for (int j = bag; j >= 2 * stones[i]; j--) {
                dp[j] = Math.max(dp[j], dp[j - 2 * stones[i]] + 2 * stones[i]);
            }
        }
        return bag - dp[bag];
    }
}
